package com.mmall.common;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

public class DataSourceAspect {
    /**
     * 在dao层方法之前获取datasource对象之前在切面中指定当前线程数据源路由的key
     */
    public void before(JoinPoint point){
        Object target = point.getTarget();
        System.out.println(target.toString());
        String method = point.getSignature().getName();
        System.out.println(method);

        Class<?>[] classz = target.getClass().getInterfaces();
//         获取方法的参数？？参数类型？
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try{
            Method m = classz[0].getMethod(method, parameterTypes);
            System.out.println(m.getAnnotations().toString());
            if (m != null && m.isAnnotationPresent(DataSource.class)) {
                DataSource data = m.getAnnotation(DataSource.class);
                System.out.println("调用方法："+m.getName());
                System.out.println("用户选择数据库库类型："+data.value());
                HandleDataSource.putDataSource(data.value());
            }else{
                //默认的数据库源Key
                //String defaultDataSourceKey = PropertiesUtil.getValue("defaultDataSourceKey");
                String defaultDataSourceKey = "dataSource1";
                //当前线程的数据源key
                String nowDataSource = HandleDataSource.getDataSource();
                if(defaultDataSourceKey==null){
                    defaultDataSourceKey = "dataSource1";
                }
                if(nowDataSource!=null&&!nowDataSource.equals(defaultDataSourceKey)){
                    System.out.println("无@DataSource默认数据库类型："+defaultDataSourceKey);
                    HandleDataSource.putDataSource(defaultDataSourceKey);
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
